#include "rtc_board.h"
#include "user_system.h"

volatile uint32_t RtcErrorTime = 0;
volatile bool RtcTiggerFlag = false;

__INTERRUPT
__HIGH_CODE
void RTC_IRQHandler(void)
{
  R8_RTC_FLAG_CTRL = (RB_RTC_TMR_CLR | RB_RTC_TRIG_CLR);
  RtcTiggerFlag = true;
}

__HIGH_CODE
static uint32_t SYS_GetClockValue(void)
{
  volatile uint32_t i = 0;

  do
  {
    i = R32_RTC_CNT_32K;
  } while (i != R32_RTC_CNT_32K);

  return (i);
}

__HIGH_CODE
static void SYS_SetPendingIRQ(void)
{
  PFIC_SetPendingIRQ(RTC_IRQn);
}

void RtcSetTiggerTime(uint32_t Time)
{
  sys_safe_access_enable();
  R32_RTC_TRIG = Time;
  sys_safe_access_disable();

  RtcTiggerFlag = false;
}

void RtcHardwareInitialization(void)
{
#if (CLK_OSC32K)
  sys_safe_access_enable();
  R8_CK32K_CONFIG &= ~(RB_CLK_OSC32K_XT | RB_CLK_XT32K_PON);
  sys_safe_access_disable();
  sys_safe_access_enable();
  R8_CK32K_CONFIG |= RB_CLK_INT32K_PON;
  sys_safe_access_disable();
  LSECFG_Current(LSE_RCur_100);
  LibraryCalibrationLSI();
#else
  sys_safe_access_enable();
  R8_CK32K_CONFIG &= ~RB_CLK_INT32K_PON;
  sys_safe_access_disable();
  sys_safe_access_enable();
  R8_CK32K_CONFIG |= RB_CLK_OSC32K_XT | RB_CLK_XT32K_PON;
  sys_safe_access_disable();
#endif

  RTC_InitTime(2020, 1, 1, 0, 0, 0);

  bleClockConfig_t ClockConfiguration = {0};
  tmos_memset(&ClockConfiguration, 0, sizeof(bleClockConfig_t));
  ClockConfiguration.ClockAccuracy = CLK_OSC32K ? 1000 : 50;
  ClockConfiguration.ClockFrequency = CAB_LSIFQ;
  ClockConfiguration.ClockMaxCount = RTC_MAX_COUNT;
  ClockConfiguration.getClockValue = SYS_GetClockValue;
  ClockConfiguration.SetPendingIRQ = SYS_SetPendingIRQ;

  TMOS_TimerInit(&ClockConfiguration);
}
